package easy;

import util.PrintUtils;

import java.util.HashMap;
import java.util.Map;

public class Solution_501 {

    private Map<Integer, Integer> map = new HashMap<>();

    public int[] findMode(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        digui(root);
        int maxCount = 0;
        for (Integer key : map.keySet()) {
            maxCount = Math.max(maxCount, map.get(key));
        }

        int count = 0;
        for (Integer key : map.keySet()) {
            if (map.get(key) == maxCount) {
                count++;
            }
        }

        int[] res = new int[count];
        int index = 0;
        for (Integer key : map.keySet()) {
            if (map.get(key) == maxCount) {
                res[index++] = key;
            }
        }
        return res;
    }

    private void digui(TreeNode node) {
        if (node == null) {
            return;
        }
        Integer count = map.getOrDefault(node.val, 0);
        count++;
        map.put(node.val, count);
        digui(node.left);
        digui(node.right);
    }

    public static void main(String[] args) {
        Solution_501 model = new Solution_501();
        Solution_501.TreeNode root = new Solution_501.TreeNode(1);
        root.right = new Solution_501.TreeNode(2);
        root.right.left = new Solution_501.TreeNode(2);

        int[] array = model.findMode(root);
        PrintUtils.arrayInt(array);
    }


    public static class TreeNode {

        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
